package com.wasu.sdk_ott.http.live;


import static com.wasu.constant.HttpDomainKt.TAG;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_LIVE_UNIFIED_AUTH;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_CONTENT_AUTHORITY;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_PLUGIN_AUTHORITY;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.RESULT_LIVE_UNIFIED_AUTH;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.wasu.UILApplication;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 调用SDK插件中的统一鉴权
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/12/27
 */
public class UnifiedAuthLoader {

    private final Uri BASE_URI = Uri.parse("content://"+PATH_WASU_SDK_CONTENT_AUTHORITY+"/"+PATH_WASU_SDK_PLUGIN_AUTHORITY);


    /**
     * 直播频道类型-统一鉴权
     * @param ppvId ppv
     * @param channelId 频道id，IPTV模式可不传
     * @return 鉴权结果的code
     */
    public String queryLiveUnifiedAuth(String ppvId, String channelId){
        Uri uri = createUri(PATH_LIVE_UNIFIED_AUTH);
        String[] param = new String[]{
                "0",
                "", "", "", "", "",
                channelId,
                "", "",
                ppvId,
                "", "", "", ""
        };
        return createRequest(UILApplication.getInstance().getApplication().getApplicationContext(), uri, param, RESULT_LIVE_UNIFIED_AUTH);
    }


    /**
     * 创建一个请求
     * @param uri 地址
     * @param param 参数
     * @return 请求结果
     */
    private String createRequest(Context context, Uri uri, String[] param, String resultPath){
        if (context == null){
            context = UILApplication.getInstance().getApplication().getApplicationContext();
        }
        try(Cursor cursor = context.getContentResolver().query(uri, param, null, null, null)) {
            if (cursor == null || !cursor.moveToNext()){
                Log.e(TAG, "createRequest, query cursor is null or not next");
                return null;
            }
            int index  = cursor.getColumnIndex(resultPath);
            if (index < 0){
                Log.e(TAG, "createRequest, query cursor column index:"+index);
                return null;
            }
            String result = cursor.getString(index);
            if (TextUtils.isEmpty(result)){
                Log.e(TAG, "createRequest, query result is null");
                return null;
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建请求uri
     */
    private Uri createUri(String uriPath){
        return BASE_URI.buildUpon().appendPath(uriPath).build();
    }
}
